<template>
	<view class=""></view>
</template>
<script >
import { getAction } from '@/api/manage'
import { mapActions,mapMutations,mapGetters,mapState } from 'vuex'
import config from '@/config'
import * as dd from 'dingtalk-jsapi'
export default {
  async created() {
		try{
			if(this.token){
				this.toPage()
				return 
			}
			if(this.$store.state.user.loginNum >=2){
				this.$modal.msgError("登录失败，请重试")
				return 
			}
			uni.showLoading({
				 title: "加载中...",
				 mask: false
			});
			// 获取第三方用户权限code
			const code = await this.getAuthCode();
			console.log(code)
			if(code){
				//系统自动登录
				await this.login(code);
				this.SET_LOGIN_NUM()
				uni.hideLoading();
			}else{
				uni.hideLoading();
				this.$modal.msgError("登录失败，请重试")
			}
		}catch(e){
			uni.hideLoading();
			//TODO handle the exception
			this.$modal.msgError("登录失败，请重试")
		}
  },
	computed:{
		...mapGetters(['token'])
	},
  methods: {
		...mapMutations(['SET_AUTH_CODE','SET_LOGIN_NUM']),
		async getAuthCode(){//根据类型获取三方用户权限
			const appType = config.appInfo.app_type
			switch (appType){
				case 'feishu':
					return this.feishu()
					break;
				case 'weixin':
				  return this.weixin()
					break;
				case 'dingtalk':
				  return this.dingding()
					break;
				default:
					break;
			}
		},
		feishu(){ //获取飞书用户权限
			// const origin = window.location.origin
			// getAction('/feishu/auth/getAuthUrl', { url: encodeURI(`${origin}/pages/LoginSSO/?url=${this.$route.query.url}&num=${num}`) }).then(res => {
			//   window.location.href = res.result
			// })
		},
		weixin(){//获取企业微信权限
			const code = this.getUrlKey('code')
			if (code) {
				return code
			} else {
				const appInfo = config.appInfo
				const redirect_uri = encodeURI(`${appInfo.ssoLocalUrl}/pages/loginSSO`)
				location.href = `${appInfo.ssoLoginUrl}?appid=${appInfo.ssoClientId}&redirect_uri=${appInfo.redirect_uri}&response_type=code&scope=snsapi_base&state=70641054-0d46-41d6-9b57-97a14dfd14d1&agentid=${appInfo.ssoAgentid}#wechat_redirect`
			}
		},
		dingding(){ //获取钉钉用户权限
			return new Promise((resolve,reject) => {		
				dd.runtime.permission.requestAuthCode({
					corpId: 'ding4681fcc26460ff5424f2f5cc6abecb85',
					// corpId:'dingc97c57c08694e2fd4ac5d6980864d335',
					onSuccess: function(result) {
						resolve(result.code)
					},
					onFail: function(err) {
						console.log(err)
						reject(err)
					}
				})
				// resolve('18c5721b168c301895ac9280c90be301')
			})
		},
		async login(code){
			this.$store.dispatch('LoginSSO', {
				authCode:code,
				thirdPlatformType:config.appInfo.app_type
			}).then(res => {
				const data = res.data
				if(data.success){
					this.toPage()
				}else{
					this.$modal.msgError("登录失败，请重试")
				}
			})
		},
		toPage(){
			this.$tab.reLaunch(`/pages/index`)
		},
		getUrlKey(name) {
			// eslint-disable-next-line no-sparse-arrays
			return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(/\+/g, '%20')) || null
		}
  }
}
</script>
<style lang="scss">
	page {
		background-color: #ffffff;
	}
</style>